package com.mach.platform.config;

import com.mach.platform.domain.WsPrincipal;
import com.mach.platform.service.WsHandshakeInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.server.support.DefaultHandshakeHandler;

import java.security.Principal;
import java.util.List;
import java.util.Map;

/**
 * 配置类
 */
@Configuration
@EnableWebSocketMessageBroker
public class wsConfig implements WebSocketMessageBrokerConfigurer {

    @Autowired
    private WsHandshakeInterceptor interceptor;


    /**
     * 配置入口
     *
     * @param registry
     */
    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/gjwl").addInterceptors(interceptor).setHandshakeHandler(new DefaultHandshakeHandler() {
            @Override
            protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler, Map<String, Object> attributes) {

                System.out.println("registerStompEndpoints:" + request.getPrincipal());
                System.out.println("registerStompEndpoints:" + attributes.get("cookie"));
                List<String> cookies = request.getHeaders().get("Cookie");

                WsPrincipal wsPrincipal = new WsPrincipal(attributes.get("cookie").toString());
                return wsPrincipal;
            }
        }).setAllowedOrigins("*").withSockJS();
    }

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableSimpleBroker("/realData");
        config.setApplicationDestinationPrefixes("/ws");
        config.setUserDestinationPrefix("/user");
    }
}
